package org.cainiaojin.service.impl;

import lombok.RequiredArgsConstructor;
import org.cainiaojin.mapper.primary.PrimaryUserMapper;
import org.cainiaojin.mapper.secondary.SecondaryUserMapper;
import org.cainiaojin.service.IUserService;
import org.cainiaojin.vo.BothUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class IUserServiceImpl implements IUserService {
    private final  PrimaryUserMapper primaryUserMapper;
    private final  SecondaryUserMapper secondaryUserMapper;

    /**
     * 测试保存用户:
     * 当程序出现异常,两个数据源都回滚
     * @param bothUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveUser(BothUser bothUser) {
        try {
            primaryUserMapper.savePrimaryUser(bothUser.getPrimaryUser());
            secondaryUserMapper.saveSecondaryUser(bothUser.getSecondaryUser());
            // 模拟程序异常
            //int i = 1 / 0;
            return "保存成功";
        } catch (Exception e) {
            // 异常会被@Transactional捕获并触发回滚
            throw new RuntimeException("保存用户失败", e);
        }
    }
    /**
     * 测试更新用户:
     * 当程序出现异常,两个数据源都回滚
     * @param bothUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateUser(BothUser bothUser) {
        try {
            primaryUserMapper.updatePrimaryUser(bothUser.getPrimaryUser());
            secondaryUserMapper.updateSecondaryUser(bothUser.getSecondaryUser());
            return "更新成功";
        } catch (Exception e) {
            // 异常会被@Transactional捕获并触发回滚
            throw new RuntimeException("更新用户失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteUser(BothUser bothUser) {
        primaryUserMapper.deletePrimaryUser(bothUser.getPrimaryUser().getId());
        secondaryUserMapper.deleteSecondaryUser(bothUser.getSecondaryUser().getId());
        return "删除成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BothUser getUser(BothUser bothUser) {
        bothUser.setPrimaryUser(primaryUserMapper.getPrimaryUser(bothUser.getPrimaryUser().getId()));
        bothUser.setSecondaryUser(secondaryUserMapper.getSecondaryUser(bothUser.getSecondaryUser().getId()));
        return bothUser;
    }

}
